import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class InsertImageDialog extends StatefulWidget {
  final bool isVideo;

  const InsertImageDialog({Key? key, this.isVideo = false}) : super(key: key);

  @override
  _InsertImageDialogState createState() => _InsertImageDialogState();
}

class _InsertImageDialogState extends State<InsertImageDialog> {
  TextEditingController link = TextEditingController();

  TextEditingController alt = TextEditingController();
  bool picked = false;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      content: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(widget.isVideo ? '视频地址' : '图片地址'),
              ElevatedButton(
                onPressed: () => getImage(),
                child: const Text(
                  '选择图片',
                  style: TextStyle(fontSize: 12),
                ),
              ),
            ],
          ),
          TextField(
            controller: link,
            decoration: const InputDecoration(
              hintText: '',
            ),
          ),
          Visibility(
            visible: !widget.isVideo,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 20.0),
                const Text('Alt text (optional)'),
                TextField(
                  controller: alt,
                  decoration: const InputDecoration(
                    hintText: '',
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.pop(context, [link.text, alt.text, picked]);
          },
          child: const Text('Done'),
        ),
        TextButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('Cancel'),
        ),
      ],
    );
  }

  Future getImage() async {
    final picker = ImagePicker();
    dynamic image;
    if (widget.isVideo) {
      image = await picker.pickVideo(source: ImageSource.gallery);
    } else {
      image = await picker.pickImage(
        source: ImageSource.gallery,
      );
    }

    if (image != null) {
      link.text = image.path;
      picked = true;
    }
  }
}
